package com.itbaizhan;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**根据用户名称模糊查找用户信息*/
public class FuzzyQueryTest01 {
    //返回一个集合，ORM编程思想
    public List<Users> fuzzyQuery(String username){
        Connection connection = null;
        PreparedStatement ps =null;
        ResultSet rs = null;
        //集合要放在try-catch外面定，才可以返回
        List<Users> list = new ArrayList<>();
        try{
            connection = JdbcUtils.getConnection();
            ps = connection.prepareStatement("select * from users where username like ?");
            //绑定参数
            ps.setString(1,username);
            //执行SQL
            rs = ps.executeQuery();
            while (rs.next()){
                Users users = new Users();
                users.setUserid(rs.getInt("userid"));
                users.setUsername(rs.getString("username"));
                users.setUsergae(rs.getInt("userage"));
                list.add(users);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JdbcUtils.closeResource(rs,ps,connection);
        }
        return list;
    }

    public static void main(String[] args) {
        FuzzyQueryTest01 fq = new FuzzyQueryTest01();
        List<Users> list = fq.fuzzyQuery("%b");
        for(Users u:list){
            System.out.println(u.getUserid()+" "+u.getUsername()+" "+ u.getUsergae());
        }
    }
}
